<template>
  <div class="note-main-container">
    <div id="nTalk_post_hiddenElement"
         style="left: -10px; top: -10px; visibility: hidden; display: none; width: 1px; height: 1px;"></div>
    <header-nav></header-nav>
    <div id="mainContent" style="background: none;">
      <div class="kanban-view">
        <div class="container-left-content">
          <div id="datePicker" style="background:#fff">
            <el-row>
              <el-col :span="20" :offset="2"><el-date-picker v-model="dateMonth" type="month" placeholder="选择月" @change="datePick">
            </el-date-picker></el-col>
              <el-col :span="2" class="arrow-to-month arrow-left"><i @click.stop="selectPreMonth" class="el-icon-caret-top"></i></el-col>
              <el-col :span="2" :offset="22" class="arrow-to-month arrow-right"><i class="el-icon-caret-bottom" @click.stop="selectNextMonth"></i></el-col>
            </el-row>
            
          </div>
          <div class="paper-list">
            <ul v-for="item in blogList">
              <li>
                <div style="overflow: hidden;" :title="item.title" @click="changeBlog(item)">
                  {{item.newTitle||(formatDay(item.time)+'号-'+item.title)}}
                </div>
              </li>
            </ul>
          </div>
        </div>
        <div class="container-right">
          <!--<div class="member">
            <div class="float-l font-13">同事</div>
            <ul class="li-float float-l">
              <li>同事 A</li>
              <li class="active">同事 B</li>
              <li>同事 C</li>
              <li>同事 D</li>
            </ul>
          </div>-->
          <div class="blog-summary-container" v-loading="loading" v-bind:class="{ isDisplayed: isDisplayed }">
            <div class="blog-summary-toggle" @click="isDisplayed = !isDisplayed">
              ||
            </div>
            <div class="blog-summary-header">
              任务总结
            </div>
            <div class="blog-summary-tasks">
              <ul>
                <li class="blog-summary-task "
                    :class="[selectedTask===task? 'selected':'']"
                    v-for="task in pTaskList"
                    @click="onSelectTask(task)" :key="task.id">
                  <span style="font-size: .8125rem; color: #333;">{{task.title}}</span>
                </li>
              </ul>
            </div>
            <div class="blog-summary-summary">
              <div>
                <div style="border-radius: 5px 5px 0 0;
                  padding: 5px;
                  border-bottom: 1px solid #ccc;
                  background: #efefef;">
                  <span style="
                  color: #333;">
                    任务总结
                  </span>
                </div>
                <div>
                  <input placeholder="请输入总结标题" v-model="summaryTitle"/>
                  <textarea placeholder="这个任务完成的如何" v-model="summaryContent"></textarea>
                </div>
              </div>
            </div>
            <div class="blog-summary-summary-control">
              <button class="el-button el-button--primary el-button--small" @click="addSummary()">添加查看</button>
              <button class="el-button el-button--primary el-button--small" @click="isDisplayed = !isDisplayed">取消
              </button>
            </div>
          </div>
          <div id="app" v-loading="loading">
            <div v-if="isViewSummaryNote" style="background-color: #fff; height: 100%; padding: 15px; overflow: auto">
              <div v-html="compiledMarkdown"></div>
            </div>
            <div style="background-color:#fff" v-else>
              <button @click="onUpdateBlog()"
                      style="color: #fff; margin: 10px; float: right"
                      class="el-button el-button--primary el-button--small">
                保存
              </button>
              <div>
              <span style="font-size: 12px; font-weight: bold;
              margin: 10px; line-height: 44px;">
                {{blog.title ? blog.title: '选择一个总结或对当日任务进行总结'}}
              </span>
              </div>
              <div style="clear: both;"></div>
              <markdown-editor :blog-content="blogContent" ref="markdownEditor"></markdown-editor>
            </div>
            
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
  import headerNav from '../../components/all/header.vue'
  import '../../../static/z39pc/js/jquery-2.1.0.js'
  import '../../../static/jslib/parsetlog_common.js'

  var marked = require('marked');
  import api from '../../api';
  import {taskAndTag} from "../../common/mixin";
  import {mixinPc} from "../../common/mixinPc";
  import moment from 'moment'
  import markdownEditor from '../../components/all/editor.md.vue'

  let initPage = function () {
    $('body').css({
      'text-align': 'left',
      'height': '100%',
      'overflow': 'hidden'
    })
  };

  export default {
    data() {
      return {
        loading: true,
        search: '',
        curDate: new Date(),
        dateMonth: new Date(),
        blogList: [],
        blog: '',
        blogContent: '',
        selectedTask: '',
        taskList: [],
        pTaskList: [],
        summaryTitle: '',
        summaryContent: '',
        noteWithSummary: '',
        isDisplayed: false,
        isViewSummaryNote: false,
        summaryNote: ''
      }
    },
    components: {
      'markdown-editor': markdownEditor,
      'header-nav': headerNav
    },
    mixins: [taskAndTag, mixinPc],
    watch: {
      'dateMonth': function () {
        this.getBlog();
      }
    },
    computed: {
      compiledMarkdown: function () {
        return marked(this.noteWithSummary, {sanitize: true})
      }
    },
    methods: {
      datePick: function (e) {
        this.curDate = e
      },
      selectPreMonth: function () {
        var d = new Date(this.curDate)
        d.setMonth(d.getMonth()-1);
        this.dateMonth = this.curDate = d
      },
      selectNextMonth: function() {
        var d = new Date(this.curDate)
        d.setMonth(d.getMonth()+1);
        this.dateMonth = this.curDate = d
      },
      getBlog: function () {
        api.blogGet({month: moment(this.dateMonth).format('YYYY-MM')}).then(data => {
          this.loading = false;
          if (data.errno !== 0) {
            this.showNotice(data.errmsg, 'warning');
            return Promise.reject(data.errmsg);
          }
          data.data = [{id:0,'newTitle':'今日总结'},...data.data];
          this.blogList = data.data;
          return Promise.resolve(data);
        })
      },
      formatDay: function (time) {
        return moment(time).format('DD') || ''
      },
      changeBlog: function (item) {
        this.loading = true;
        this.blog = item;
        this.isViewSummaryNote = false;
        const params = {
          id: item.id,
          content: 1,
        };

        this.loading = true;
        api.blogGet(params).then(data => {
          this.loading = false;
          if (data.errno !== 0) {
            this.showNotice(data.errmsg, 'warning');
            return Promise.reject(data.errmsg);
          }
          this.blogContent = data.data.content;
          
          this.getTasks(item['time']);
          return Promise.resolve(data);
        })
      },
      onUpdateBlog: function () {
        if (!(this.blog)) {
          return;
        }
        if (!this.blog.id) {
          this.showNotice('不能保存今日总结', 'error');
          return;
        }
        this.blogContent = this.$refs.markdownEditor.getContent();
        this.loading = true;
        const param = {
          "id": this.blog.id,
          "content": this.blogContent
        };
        api.blogContentUpdate(param).then(data => {
          this.loading = false;
          if (data.errno !== 0) {
            this.showNotice(data.errmsg, 'error');
            return Promise.reject(data.errmsg);
          }
          this.showNotice('保存成功', 'success');
          return Promise.resolve(data);
        });
      },
      getTasks: function (day=new Date().toISOString().substr(0, 10)) {
        const param = {
          day: day,
        };

        return api.taskGet(param).then(data => {
          if (data.errno !== 0) {
            this.showNotice(data.errmsg, 'error');
            return Promise.reject(data.errmsg);
          }
          this.taskList = data.data;
          this.pTaskList = data.data.filter(task => task.parid === null);
          return Promise.resolve(data);
        })
      },
      addSummary: function () {
        if (!(this.selectedTask)) {
          this.showNotice('请选择一个任务', 'warn');
          return;
        }
        if (!(this.summaryTitle)) {
          this.showNotice('请输入总结标题', 'warn');
          return;
        }
        const currentDate = new Date().toISOString().substr(0, 10);
        const _this = this;
        this.taskAdd({
          parid: this.selectedTask.id,
          title: this.summaryTitle,
          desc: this.summaryContent,
          state: 'done',
        }, {summary: "", done: currentDate}).then(data => {
          let day = _this.blog['time'];
          _this.summaryTitle = '';
          _this.summaryContent = '';
          _this.blog = '';
          _this.isDisplayed = false;
          _this.isViewSummaryNote = true;
          
          this.getTasks(day).then(() => this.previewSummaryNote());
        })
      },

      convertOldTaskListToNew(){
        let list = [];
        const cTaskList = this.taskList.filter(task => task.parid !== null);
        const newTaskList = Object.assign(this.pTaskList);
        newTaskList.forEach( pTask => {
          pTask.tasks =  pTask.tasks ?  pTask.tasks : [];
          cTaskList.forEach( cTask => {
            if(cTask.parid === pTask.id) {
              const tCTask = {
                "type": "task",
                "title": cTask.title,
                "desc": cTask.desc,
                "status": cTask.state,
                "tags": {
                },
                tasks: [],
              };
              if(cTask.tags) {
                cTask.tags.forEach(tag => {
                  tCTask.tags[tag.key] = tag.value;
                });
              }
              pTask.tasks.push(tCTask);
            }
          })
        });

        newTaskList.forEach(newTask => {
          const tmpPTask = {
            "type": "task",
            "title": newTask.title,
            "desc": newTask.desc,
            "status": newTask.state,
            "tags": {
            },
            tasks: newTask.tasks
          };
          newTask.tags.forEach(tag => {
            tmpPTask.tags[tag.key] = tag.value;
          });
          list.push(tmpPTask);
        });
        return list;
      },
      previewSummaryNote() {
        var str = "";
        str = log2md(this.convertOldTaskListToNew());
        this.noteWithSummary = str;
        return str;
      },
      onSelectTask: function (task) {
        this.selectedTask = task;
      },
    },
    mounted() {
      this.getBlog();
      this.getTasks();
      initPage();
    }
  }
</script>
<style>
  @import "../../../static/z39pc/css/noteMain.css";
  @import "../../../static/z39pc/css/docute.css";
  @import "../../../static/z39pc/css/mycss/note.css";
  @import '~simplemde/dist/simplemde.min.css';
  .note-main-container #mainContent .container-left-content {
    width: 311px;
  }
  .note-main-container #mainContent .container-right {
    left: 311px;
  }
  #datePicker {
    position: relative;
  }
  #datePicker input {
    border: none;
  }
  #datePicker .arrow-to-month {
    cursor: pointer;
    position: absolute;
    left: 0;
    top: 0;
    height: 2.7rem;
    padding-top: 0.4rem;
    text-align: center;
    z-index: 4000;
  }
  .note-main-container #mainContent .blog-summary-container .blog-summary-task{
    box-sizing: border-box;
    border: 1px solid #ededed;
    border-bottom-color: #d8d8d8;
    cursor: pointer;
  }
  .note-main-container #mainContent .blog-summary-container .blog-summary-task.selected {
    background: #ffebd8;
    border: 1px solid #ff7e00 !important;
    color: #ff7e00;
  }
</style>
